package com.fzkj.juc.prodconsumer;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @DESCRIPTION
 */
public class ProdConsumer_V2_blockqueue_demo {

    public static void main(String[] args) {

        Share share = new Share(new ArrayBlockingQueue<>(3));
        new Thread(() -> {
            try{
                share.product();
            }catch (Exception e){
                e.printStackTrace();
            }
        }, "product").start();
        new Thread(() -> {
            try{
                share.consumer();
            }catch (Exception e){
                e.printStackTrace();
            }
        }, "consumer").start();

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        share.stop();
    }

}

class Share {
    private AtomicInteger number = new AtomicInteger();

    private BlockingQueue<String> queue = null;

    private volatile Boolean PRODUCT = true;

    public Share(BlockingQueue<String> queue){
        this.queue = queue;
    }

    public void product() throws InterruptedException {
        String data = null;
        boolean ret = false;
        while (PRODUCT){
            //
            data = number.getAndIncrement() + "";
            ret = queue.offer(data, 2L, TimeUnit.SECONDS);
            System.out.println("生产成功 -> " + ret);
            System.out.println("生产的是 -> " + data);
            Thread.sleep(1000);
        }
    }

    public void consumer() throws InterruptedException {
        String poll = null;
        while (PRODUCT){
            //
            poll = queue.poll(2L, TimeUnit.SECONDS);
            System.out.println("消费成功 -> " + poll);
        }
    }

    public void stop(){
        PRODUCT = false;
    }
}
